package com.tust.androidbbsclient.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tust.androidbbsclient.LoginActivity;
import com.tust.androidbbsclient.PersonArtListActivity;
import com.tust.androidbbsclient.PersonComListActivity;
import com.tust.androidbbsclient.R;
import com.tust.androidbbsclient.SettingActivity;
import com.tust.androidbbsclient.tool.Application;
import com.tust.androidbbsclient.tool.Tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PersonFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PersonFragment extends Fragment {
    private Toast toast;
    private Context context;
    private int UID;

    TextView textViewPersonUfavorNum;
    TextView textViewPersonUcollNum;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//获取用户点赞量请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("点赞量：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else {
                    //TextView textViewPersonUfavorNum = getView().findViewById(R.id.tv_personUfavorNum);
                    textViewPersonUfavorNum.setText(strMsg);
                }
            } else if (msg.what == 2) {//获取用户收藏量请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("收藏量：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else {
                    //TextView textViewPersonUcollNum = getView().findViewById(R.id.tv_personUcollNum);
                    textViewPersonUcollNum.setText(strMsg);
                }
            }
        }
    };

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public PersonFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PersonFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PersonFragment newInstance(String param1, String param2) {
        PersonFragment fragment = new PersonFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_person, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getContext();

        textViewPersonUfavorNum = getView().findViewById(R.id.tv_personUfavorNum);
        textViewPersonUcollNum = getView().findViewById(R.id.tv_personUcollNum);

        TextView textViewPersonUname = view.findViewById(R.id.tv_personUname);
        TextView textViewPersonUgender = view.findViewById(R.id.tv_personUgender);
        TextView textViewPersonUbanLevel = view.findViewById(R.id.tv_personUbanLevel);
        TextView textViewPersonUint = view.findViewById(R.id.tv_personUint);
        LinearLayout linearLayoutPersonFavorlist = view.findViewById(R.id.ll_personFavorList);
        LinearLayout linearLayoutPersonColllist = view.findViewById(R.id.ll_personCollList);
        LinearLayout linearLayoutPersonSubList = view.findViewById(R.id.ll_personSubList);
        LinearLayout linearLayoutPersonComList = view.findViewById(R.id.ll_personComList);
        LinearLayout linearLayoutPersonSetting = view.findViewById(R.id.ll_personSetting);
        Button buttonPersonLogout = view.findViewById(R.id.btn_personLogout);

        //从Application中获取用户信息
        Application application = (Application) getActivity().getApplication();
        UID = application.user.getUID();
        textViewPersonUname.setText(application.user.getUname());
        if (application.user.getUgender().equals("男")) {
            textViewPersonUgender.setText("♂");
            textViewPersonUgender.setTextColor(ContextCompat.getColor(context, R.color.royalblue));
        }
        else if (application.user.getUgender().equals("女")) {
            textViewPersonUgender.setText("♀");
            textViewPersonUgender.setTextColor(ContextCompat.getColor(context, R.color.red));
        }
        else if (application.user.getUgender().equals("")) textViewPersonUgender.setText("");
        if (application.user.getUbanLevel() == -1) textViewPersonUbanLevel.setText("禁言中");
        else textViewPersonUbanLevel.setText("");
        textViewPersonUint.setText(application.user.getUint());

        //发送获取用户点赞量请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/getUfavorNum.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "UID=" + UID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //发送获取用户收藏量请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 2;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/getUcollNum.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "UID=" + UID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 2;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //点赞列表文本监听事件
        linearLayoutPersonFavorlist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动，带有whatArtList、UID参数
                Intent intent = new Intent(getActivity(), PersonArtListActivity.class);
                intent.putExtra("whatArtList", "favorList");
                intent.putExtra("UID", UID);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //收藏列表文本监听事件
        linearLayoutPersonColllist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动，带有whatArtList、UID参数
                Intent intent = new Intent(getActivity(),PersonArtListActivity.class);
                intent.putExtra("whatArtList", "collList");
                intent.putExtra("UID", UID);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //个人发布文本监听事件
        linearLayoutPersonSubList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动，带有whatArtList、UID参数
                Intent intent = new Intent(getActivity(),PersonArtListActivity.class);
                intent.putExtra("whatArtList", "perSubList");
                intent.putExtra("UID", UID);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //个人评论文本监听事件
        linearLayoutPersonComList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动
                Intent intent = new Intent(getActivity(), PersonComListActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //个人设置文本监听事件
        linearLayoutPersonSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //退出账号按钮监听事件
        buttonPersonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
